package com.eduhzy.ttw.clazz.mvp.presenter;

import android.app.Application;
import android.os.Message;

import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.SPUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eduhzy.ttw.clazz.mvp.contract.AddGroupContract;
import com.eduhzy.ttw.clazz.mvp.model.entity.ReviewStudentData;
import com.eduhzy.ttw.commonres.utils.RxUtil;
import com.eduhzy.ttw.commonsdk.core.Constants;
import com.eduhzy.ttw.commonsdk.core.EventBusTags;
import com.eduhzy.ttw.commonsdk.core.RouterHub;
import com.eduhzy.ttw.commonsdk.entity.CommonData;
import com.eduhzy.ttw.commonsdk.holder.AutoBaseViewHolder;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.RxLifecycleUtils;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;

import org.simple.eventbus.EventBus;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;


/**
 * @author xubo
 * @date 2018-12-7 9:15:38
 */
@ActivityScope
public class AddGroupPresenter extends BasePresenter<AddGroupContract.Model, AddGroupContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;
    @Inject
    BaseQuickAdapter<ReviewStudentData, AutoBaseViewHolder> mAdapter;

    @Inject
    public AddGroupPresenter(AddGroupContract.Model model, AddGroupContract.View rootView) {
        super(model, rootView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }


    public void getUngroupUser(int classId, int teamType) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("teacherId", SPUtils.getInstance().getString(Constants.USERID));
        map.put("classId", classId);
        map.put("teamType", teamType);
        mModel.getUngroupUser(map)
                .subscribeOn(Schedulers.io())
                .retryWhen(new RetryWithDelay(2, 3))
                .doOnSubscribe(disposable -> {
                    //显示下拉刷新的进度条
                    mRootView.showLoading();
                }).subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(() -> {
                    //隐藏下拉刷新的进度条
                    mRootView.hideLoading();
                })
                //使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<CommonData<List<ReviewStudentData>>>(mErrorHandler) {
                    @Override
                    public void onNext(CommonData<List<ReviewStudentData>> commonData) {
                        if (commonData.isResult()) {
                            if (ObjectUtils.isEmpty(commonData.getData())) {
                                mRootView.showMessage("学生已分配完毕，不能继续分组");
                                mRootView.killMyself();
                            } else {
                                for (ReviewStudentData studentData : commonData.getData()) {
                                    studentData.setCheck(false);
                                }
                                mAdapter.setNewData(commonData.getData());
                            }
                        } else {
                            mRootView.showMessage(commonData.getMessage());
                        }
                    }
                });
    }

    public void saveTeam(int classId, int teamType, String teamName, String studentIds) {
        QMUITipDialog tipDialog = RxUtil.showLoading(mRootView.getActivity(), "请稍后···");
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("classId", classId);
        map.put("teacherId", SPUtils.getInstance().getString(Constants.USERID));
        map.put("teamType", teamType);
        map.put("teamName", teamName);
        map.put("studentIds", studentIds);
        mModel.saveTeam(map)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> {
                    //显示下拉刷新的进度条
                    tipDialog.show();
                }).subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(() -> {
                    //隐藏下拉刷新的进度条
                    tipDialog.dismiss();
                })
                //使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<CommonData<Map>>(mErrorHandler) {
                    @Override
                    public void onNext(CommonData<Map> commonData) {
                        mRootView.showMessage(commonData.getMessage());
                        if (commonData.isResult()) {
                            Message msg = Message.obtain();
                            msg.what = EventBusTags.EDIT_GROUP_SUCCESS;
                            EventBus.getDefault().post(msg, RouterHub.CLAZZ_GROUPREVIEWFRAGMENT);
                            EventBus.getDefault().post(msg, RouterHub.CLAZZ_GROUPLISTACTIVITY);

                            mRootView.killMyself();
                        }
                    }
                });

    }
}
